<template>
  <div class="create-event-page">
    <!-- 导航栏 -->
    <van-nav-bar
      :title="isEdit ? '修改活动' : '创建活动'"
      left-arrow
      @click-left="goBack"
      class="nav-bar"
    />

    <!-- 表单 -->
    <div class="form-container">
      <van-form @submit="onSubmit">
        <!-- 活动类别 -->
        <van-field
          :value="selectedCategoryText"
          label="活动类别"
          required
          readonly
          is-link
          placeholder="请选择活动类别"
          @click="showCategoryPicker = true"
        />
        <van-popup v-model="showCategoryPicker" position="bottom">
          <van-picker
            :columns="categories"
            show-toolbar
            title="选择活动类别"
            @confirm="onCategoryConfirm"
            @cancel="() => (showCategoryPicker = false)"
          />
        </van-popup>

        <!-- 活动名称 -->
        <van-field
          v-model="form.name"
          label="活动名称"
          required
          placeholder="请输入活动名称"
        />

        <!-- 活动人数 -->
        <van-field
          v-model="form.number"
          label="活动人数"
          required
          type="number"
          placeholder="请输入活动人数"
        />

        <!-- 活动地点 -->
        <van-field
          v-model="form.location"
          label="活动地点"
          required
          placeholder="请输入活动地点"
        />

        <!-- 活动描述 -->
        <van-field
          v-model="form.description"
          label="活动描述"
          required
          type="textarea"
          rows="3"
          autosize
          placeholder="请输入活动描述"
        />

        <!-- 活动时间选择 -->
        <div class="datetime-picker-field">
          <van-field
            label="开始时间"
            readonly
            clickable
            required
            :value="form.startTime ? formatDate(form.startTime) : ''"
            placeholder="请选择开始时间"
            @click="showStartTimePicker = true"
          />
          <van-popup v-model="showStartTimePicker" position="bottom">
            <van-datetime-picker
              v-model="form.startTime"
              type="datetime"
              title="选择开始时间"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onStartTimeConfirm"
              @cancel="() => (showStartTimePicker = false)"
            />
          </van-popup>

          <van-field
            label="结束时间"
            readonly
            clickable
            required
            :value="form.endTime ? formatDate(form.endTime) : ''"
            placeholder="请选择结束时间"
            @click="showEndTimePicker = true"
          />
          <van-popup v-model="showEndTimePicker" position="bottom">
            <van-datetime-picker
              v-model="form.endTime"
              type="datetime"
              title="选择结束时间"
              :min-date="form.startTime || minDate"
              :max-date="maxDate"
              @confirm="onEndTimeConfirm"
              @cancel="() => (showEndTimePicker = false)"
            />
          </van-popup>
        </div>

        <van-field name="uploader" label="活动图片">
          <template #input>
            <van-uploader
              :file-list="fileList"
              :after-read="onImageChange"
              :max-count="5"
              :preview-image="true"
              accept="image/*"
              @delete="onDeleteImage"
              multiple
              show-upload
            />
          </template>
        </van-field>

        <!-- 活动时长 -->
        <van-field
          v-model="form.hours"
          label="活动时长"
          required
          type="number"
          placeholder="请输入活动志愿时长（小时）"
        />

        <!-- 提交按钮 -->
        <div class="submit-button">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            class="custom-button"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
  
  <script>
import {
  NavBar,
  Field,
  Form,
  Button,
  Picker,
  Popup,
  DatetimePicker,
  Uploader,
} from "vant";
import activityApi from "@/api/activity.js";
import fileApi from "@/api/file.js";

export default {
  components: {
    "van-nav-bar": NavBar,
    "van-field": Field,
    "van-form": Form,
    "van-button": Button,
    "van-picker": Picker,
    "van-popup": Popup,
    "van-datetime-picker": DatetimePicker,
    "van-uploader": Uploader,
  },
  data() {
    return {
      form: {
        id: "",
        typeId: null,
        name: "",
        number: null,
        location: "",
        description: "",
        pics: [],
        startTime: null,
        endTime: null,
        hours: null,
      },
      isEdit: false, // 是否为编辑状态
      categories: [], // 活动类别
      showCategoryPicker: false,
      showStartTimePicker: false,
      showEndTimePicker: false,
      selectedCategoryText: "", // 保存选择的类别文本
      minDate: new Date(),
      maxDate: new Date(),
      fileList: [], // 显示在组件中的图片列表
      eventId: "",
    };
  },
  mounted() {
    this.fetchCategories();
    const currentDate = new Date();
    this.minDate = new Date(currentDate.getFullYear() - 1, 0, 1);
    this.maxDate = new Date(currentDate.getFullYear() + 1, 11, 31);

    this.eventId = this.$route.query.id;
    if (this.eventId) {
      this.isEdit = true;
      this.fetchEventDetails(this.eventId);
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    fetchCategories() {
      activityApi.getActivityTypes().then((res) => {
        this.categories = res.map((category) => ({
          text: category.type,
          id: category.id,
        }));
      });
    },
    async fetchEventDetails(eventId) {
      try {
        activityApi.getEventById(eventId).then((res) => {
          console.log(res);
          this.form = {
            id: this.eventId,
            typeId: res.typeId,
            name: res.name,
            number: res.number,
            location: res.location,
            description: res.description,
            pics: JSON.parse(res.pics),
            startTime: new Date(res.startTime), // 直接赋值为 Date 对象
            endTime: new Date(res.endTime), // 直接赋值为 Date 对象
            // startTime: this.formatDate1(res.startTime),
            // endTime: this.formatDate1(res.endTime),
            hours: res.hours,
          };
          // 根据返回的 categoryId 从 categories 数组中获取类别名称
          const category = this.categories.find((cat) => cat.id === res.typeId);
          if (category) {
            this.selectedCategoryText = category.text;
          }
          // 填充图片列表
          this.fileList = this.form.pics.map((url) => ({ url })); // 更新图片列表
        });
        // this.selectedCategoryText = event.categoryName; // 假设API返回的活动类别名
      } catch (error) {
        console.error("获取活动详情失败", error);
      }
    },
    onCategoryConfirm(category) {
      this.form.typeId = category.id; // 提交时使用 ID
      this.selectedCategoryText = category.text; // 显示文本
      this.showCategoryPicker = false;
    },
    onStartTimeConfirm(value) {
      this.form.startTime = value;
      this.showStartTimePicker = false;
    },
    onEndTimeConfirm(value) {
      this.form.endTime = value;
      this.showEndTimePicker = false;
    },
    // 处理图片上传
    async onImageChange(fileObj) {
      const file = fileObj.file;
      if (file && file instanceof File) {
        try {
          // 调用文件上传接口
          const res = await fileApi.fileUpload(file);

          // 更新 fileList（前端展示）
          this.fileList.push({ url: res });

          // 更新 form.pics（后端提交格式）
          this.form.pics.push(res);
        } catch (err) {
          console.error("图片上传失败:", err);
          this.$toast.fail("图片上传失败");
        }
      } else {
        console.error("无效的文件上传");
      }
    },
    getObjectName(fileUrl) {
      const bucketUrl = "https://volunteersystem.oss-cn-beijing.aliyuncs.com/";
      return fileUrl.replace(bucketUrl, "");
    },
    async onDeleteImage(file) {
      try {
        const fileUrl = file.url;

        // 删除 OSS 图片（如果需要调用后端接口）
        const objectName = this.getObjectName(fileUrl);
        if (objectName) {
          await fileApi.deleteImage(objectName);
          console.log("OSS 图片已删除");
        }

        // 更新 fileList 和 form.pics
        this.fileList = this.fileList.filter((item) => item.url !== fileUrl);
        this.form.pics = this.form.pics.filter((url) => url !== fileUrl);

        console.log("当前图片列表:", this.form.pics);
      } catch (err) {
        console.error("删除图片失败:", err);
        this.$toast.fail("删除图片失败");
      }
    },
    onSubmit() {
      console.log(this.form);

      this.form.startTime = this.formatDate(this.form.startTime);
      this.form.endTime = this.formatDate(this.form.endTime);
      this.form.pics = JSON.stringify(this.form.pics);
      if (this.isEdit) {
        activityApi.updateEvent(this.form, this.eventId);
        this.$toast.success("活动修改成功！");
      } else {
        activityApi.createEventOrganizer(this.form);
        this.$toast.success("活动创建成功！");
      }
      this.$router.push("/organizer/activity");
    },

    formatDate(date) {
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")} ${d
        .getHours()
        .toString()
        .padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}:${d
        .getSeconds()
        .toString()
        .padStart(2, "0")}`;
    },
    formatDate1(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0"); // 保证月份是两位数
      const day = d.getDate().toString().padStart(2, "0"); // 保证日期是两位数
      const hours = d.getHours().toString().padStart(2, "0");
      const minutes = d.getMinutes().toString().padStart(2, "0");
      const seconds = d.getSeconds().toString().padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
};
</script>
  
  <style scoped>
  .custom-button {
  background-color: #007aff !important; /* 选择你喜欢的蓝色 */
  color: #fff; /* 文本颜色 */
}
.create-event-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.form-container {
  flex: 1;
  padding: 4vw;
  background-color: #fff;
  border-radius: 8px;
  margin: 2vh 4vw;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.datetime-picker-field {
  margin-bottom: 2vh;
}

.uploader-field {
  margin-bottom: 2vh;
}

.uploader-label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.submit-button {
  margin-top: 2vh;
}
</style>
  